package com.fourth.util.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.fourth.dto.UserDTO;
import com.fourth.util.UserHolder;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.fourth.util.Constants.LOGIN_USER_KEY;
import static com.fourth.util.Constants.LOGIN_USER_TTL;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 邓建波
 */
public class LoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate redisTemplate;

    public LoginInterceptor(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        //TODO 1.获取Token
        String token = request.getHeader("access-token");
        //TODO 2.判断Token是否为空
        if(StrUtil.isBlank(token)){
            //TODO 2.1如果为空，重定向至登录页面,并拦截请求
            response.sendRedirect("/");
            return false;
        }
        //TODO 3.基于token获取用户
        String key = LOGIN_USER_KEY + token;
        final Map<Object, Object> userMap = redisTemplate.opsForHash().entries(key);
        //TODO 4.判断redis中的用户信息是否过期
        if(userMap.isEmpty()){
            //TODO 4.1如果用户信息过期，重定向至登录页面，并拦截请求
            response.sendRedirect("/");
            return false;
        }
        //TODO 5.将map信息转换为UserDTO对象
        UserDTO user = BeanUtil.fillBeanWithMap(userMap,new UserDTO(),false);
        //TODO 6.存入ThreadLocal中
        UserHolder.saveUser(user);
        //TODO 7.刷新用户信息超时时间
        redisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MILLISECONDS);
        //TODO 8.放行
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex){
        UserHolder.removeUser();
    }
}
